package resource
{
	import flash.utils.ByteArray;
	
	public class XMLResource
	{
		private var rootName: String;
		private var xmlData : XML;
		private var loadObject: Object;
		
		public function XMLResource(data: Object, rootName:String="XML"){
			this.rootName = rootName;
			if (data is ByteArray){
				data = (data as ByteArray).readUTFBytes((data as ByteArray).length);
			}
			try{
				this.xmlData = new XML(data);
				this.loadObject = this.xmlToObject(this.xmlData, true);
			}catch(e: TypeError){
				trace("Pasing XML Error!" + e.toString());	
			}
		}
		
		public function toObject(objectName: String): Object{
			if (this.loadObject[this.rootName]) {
				if (this.loadObject[this.rootName][objectName])
					return this.loadObject[this.rootName][objectName];
			}
			return null;
		}
		
		private function xmlToObject(srcData: XML, ignoreNamespace: Boolean = false): Object{
			if(srcData){
				var obj: Object = {};
				pNode(srcData, obj, ignoreNamespace);
				return obj;
			}
			return null;
		}
		
		public function pNode(node: XML, obj: Object, ignoreNamespace: Boolean): void{
			if (ignoreNamespace) node.setNamespace("");
			var nodeName: String = node.name().toString();
			var o: Object = {};
			var j: Object;
			
			if(node.attributes().length() > 0){
				for(j in node.attributes()){
					o[node.attributes()[j].name().toString()] = node.attributes()[j];
				}
				
				if(node.children().length() <= 1 && o["value"] == undefined){
					o["value"] = node.toString();
				}
			}else{
				if(node.children().length() <= 1 && !node.hasComplexContent()){
					o = node.toString();
				}
			}
			
			if(obj[nodeName] == undefined)
				obj[nodeName] = o;
			else{
				if(obj[nodeName] is Array)
					obj[nodeName].push(o)
				else
					obj[nodeName]  = [obj[nodeName], o];
			}
			try{
				toObj(node as XML, obj[nodeName], ignoreNamespace);
			}catch(e: TypeError){
				
			};
		}
		
		private function toObj(dp:XML,obj:Object,ignoreNamespace:Boolean):void  
		{   
			var i:int,j:int,nodeName:String,nl:int;   
			nl = dp.children().length();   
			for(i=0;i<nl;i++) 
			{   
				var node:XML = dp.children()[i];   
				if(obj is Array)   
				{   
					pNode(node,obj[obj.length-1],ignoreNamespace);   
				}   
				else  
					pNode(node,obj,ignoreNamespace);   
			}   
		}
	}
}